package com.kangaroo.myhome.config;

import java.io.PrintWriter;

import com.kangaroo.myhome.model.TSUserloginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.kangaroo.myhome.security.JwtAuthenticationFilter;
import com.kangaroo.myhome.security.JwtAuthenticationProvider;
import com.kangaroo.myhome.security.JwtLoginFilter;
import com.kangaroo.myhome.security.JwtUserDetails;
import com.kangaroo.myhome.service.impl.UserLoginInfoService;
import com.kangaroo.myhome.utils.JsonUtils;
import com.kangaroo.myhome.utils.SpringUtils;
import com.kangaroo.myhome.vo.ResponseModel;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义登录身份认证组件
        auth.authenticationProvider(new JwtAuthenticationProvider(userDetailsService));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 禁用 csrf, 由于使用的是JWT，我们这里不需要csrf
        http.cors().and().csrf().disable().authorizeRequests()
            // 跨域预检请求
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            // 登录URL
            .antMatchers("/login").permitAll()
            //
            .antMatchers("/loginOut").permitAll()
            // swagger
            .antMatchers("/swagger**/**").permitAll()
            //
            .antMatchers("/webjars/**").permitAll()
            //
            .antMatchers("/v2/**").permitAll().antMatchers("/task/**").permitAll()
            //
            .antMatchers("/upload/**").permitAll()
            //
            .antMatchers("/projectXunCha/**").permitAll()
            //
            .antMatchers("/insp/**").permitAll()
                .antMatchers("/**/**").permitAll()
            // 其他所有请求需要身份认证

            .anyRequest().authenticated();
        // 退出登录处理器
        http.logout().logoutSuccessHandler((request, response, authentication) -> {
            ResponseModel model = new ResponseModel();

            // 保存登录信息
            TSUserloginInfo tSUserloginInfo = new TSUserloginInfo();
            if (authentication != null) {
                String userName = ((JwtUserDetails)authentication.getPrincipal()).getUsername();
                tSUserloginInfo.setWorkNo(userName);
                UserLoginInfoService userLoginInfoService = SpringUtils.getBean(UserLoginInfoService.class);
                userLoginInfoService.updateLoginOutInfo(tSUserloginInfo);

            }
            model.setCode(200);
            model.setData(authentication);
            model.setMessage("退出成功");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(JsonUtils.object2Json(model));
            out.flush();
            out.close();
        });
        // 开启登录认证流程过滤器
        http.addFilterBefore(new JwtLoginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
        // 访问控制时登录状态检查过滤器
        http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()),
            UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}